
import {isObject} from '../../base';


var stringifyPrimitive = function(v) {
    switch (typeof v) {
        case 'string':
            return v;

        case 'boolean':
            return v ? 'true' : 'false';

        case 'number':
            return isFinite(v) ? v : '';

        default:
            return '';
    }
};

/**
 * suffix：参数名后缀，如[0]
 */
export default function encode(obj, sep, eq, name,suffix) {
    sep = sep || '&';
    eq = eq || '=';
    name = name || "";
    suffix = suffix || "";

    if (!obj) {
        obj = undefined;
    }

    if(Array.isArray(obj)) {
        var r = [];
        for(var n=0; n < obj.length; n++){
            var ks = name + suffix;

            r.push(encode(obj[n],sep,eq,ks,"[" + n + "]"));
        }

        return r.join(sep);
    }

    if (typeof obj === 'object') {
        if(name){
            name = name + suffix + ".";
        }
        return Object.keys(obj).map(function(k) {
            //var ks = encodeURIComponent(stringifyPrimitive(name + k));
            var ks = name + k;

            if(isObject(obj[k])){
                return encode(obj[k], sep, eq, ks);
            }else{
                return encodeURIComponent(ks) + eq + encodeURIComponent(stringifyPrimitive(obj[k]));
            }
        }).join(sep);

    }

    if (!name) return '';
    return encodeURIComponent(stringifyPrimitive(name)) + eq +
        encodeURIComponent(stringifyPrimitive(obj));
}